#include <iostream>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
//typedef websocketpp::server<websocketpp::config::asio> wsserver_t;
using wsserver_t=websocketpp::server<websocketpp::config::asio>; 

//请求相应的回调函数
void http_callback(wsserver_t* server,websocketpp::connection_hdl hdl)
{
    //获取请求信息(通过server获取connection_ptr，从而得到各种信息)
    wsserver_t::connection_ptr conn = server->get_connection();
    //请求正文打印
    std::cout<<"body:"<<conn->get_request_body()<<std::endl;
    //得到请求对象：websocketpp::http::parser::request req=请求对象
    websocketpp::http::parser::request req=conn->get_request();
    //打印请求方法、uri(资源路径)
    std::cout<<"uri:"<<req.get_uri()<<std::endl;

    //报文包装
    //1.设置body，即html页面
    std::string body="<html><body><h1>Hello World</h1></body></html>";
    conn->set_body(body);
    //2.设置头部字段
    conn->append_header("Content-Type","text/html");
    //3.设置状态码
    conn->set_status(websocketpp::http::status_code::ok);

}
//握手成功
void open_callback(wsserver_t* server,websocketpp::connection_hdl hdl)
{
    //打印日志信息
    std::cout<<"enter open_callback"<<std::endl;
}
//断开连接
void close_callback(wsserver_t* server,websocketpp::connection_hdl hdl)
{
    //打印日志信息
    std::cout<<"enter close_callback"<<std::endl;
}
void message_callback(wsserver_t* server,websocketpp::connection_hdl hdl,wsserver_t::message_ptr msg)
{
    //获取请求信息(即连接对象)
    wsserver_t::connection_ptr conn = server->get_connection();
    //获取客户端信息并打印
    std::cout<<msg->get_payload()<<std::endl;
    //处理，发送
    std::string send_str="client say:"+msg->get_payload();
    conn->send(send_str,websocketpp::frame::opcode::text);
}
int main()
{
    //实例化server对象
    wsserver_t server;
    
    //设置日志等级
    server.set_access_channels(websocketpp::log::alevel::none);
    
    //初始化asio
    server.init_asio();
    server.set_reuse_addr(true);
    
    //设置回调接口
    server.set_http_handler(std::bind(http_callback,&server,std::placeholders::_1));
    server.set_open_handler(std::bind(open_callback,&server,std::placeholders::_1));
    server.set_close_handler(std::bind(close_callback,&server,std::placeholders::_1));
    server.set_message_handler(std::bind(message_callback,&server,std::placeholders::_1,std::placeholders::_2));

    //设置监听接口
    server.listen(8585);

    //开始获取连接
    server.start_accept();
    
    //启动服务器
    server.run();
    return 0;
}
